import axios from 'axios'
import { message } from 'antd'
import { getConfig } from '@config/env'
import { storage } from '@utils/storage'

const { apiBaseUrl } = getConfig()

export const http = axios.create({
  baseURL: apiBaseUrl,
  timeout: 15_000,
})

http.interceptors.request.use(
  (config) => {
    const token = storage.get<string | null>('erai_token')
    if (token) {
      config.headers.Authorization = `Bearer ${token}`
    }
    return config
  },
  (error) => Promise.reject(error),
)

http.interceptors.response.use(
  (response) => response,
  (error) => {
    const status = error.response?.status
    if (status === 401) {
      message.error('登录状态已过期，请重新登录')
    } else if (status && status >= 500) {
      message.error('服务器繁忙，请稍后重试')
    }
    return Promise.reject(error)
  },
)


